<?php
/*
 * [generator id='Generator' usercap='edit_plugins' ownercap='edit_plugins']
 *
 */

namespace WebApper\Shortcode;

class Generator extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'generator';
	protected $defaults = array(
		'id' => null,					// The unique ID to use for the shortcode. Default: none. Required.
		'usercap' => 'edit_plugins',	// The minimum user capability required to access the Web-Apper Generator. OPTIONS: 'logged_out', 'read', 'edit_posts', 'edit_others_posts', 'edit_users', 'edit_pages', 'edit_plugins'. Default: 'edit_plugins'.
		'ownercap' => 'edit_plugins',	// The minimum user capability required to access the singleview, for the user's own records (when the user is the post author). OPTIONS: 'logged_out', 'read', 'edit_posts', 'edit_others_posts', 'edit_users', 'edit_pages', 'edit_plugins'. Default 'edit_posts'.
	);
	protected $web_apper_cpts_options;
	protected $web_apper_fieldsets_options;
	protected $web_apper_fieldsets;
	protected $web_apper_fields_options;
	protected $wp_user_caps;

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Get shortcode attributes
			extract( shortcode_atts( $this->defaults, $atts ) );

		// Check for required shortcode attributes
			$msg = $this->has_req_attrs( $atts );
			if ( $msg !== true )
				return $msg;

        // Check if current user has proper privileges
			if ( !$this->user_has_cap( $usercap, $ownercap ) )
				return;

		// Build the bootstrap tab component html
			global $post;

			?>
			<ul class="nav nav-pills">
				<li<?php if ( $_GET['shortcode'] == null ) echo ' class="active"'; ?>><a href="<?php echo get_permalink($post->ID); ?>"><i class="icon-home"></i> Getting Started</a></li>
				<li<?php if ( $_GET['shortcode'] == 'form' ) echo ' class="active"'; ?>><a href="<?php echo get_permalink($post->ID); ?>/?shortcode=recordform"><i class="icon-list"></i> Form shortcode</a></li>
				<li<?php if ( $_GET['shortcode'] == 'indextable' ) echo ' class="active"'; ?>><a href="<?php echo get_permalink($post->ID); ?>/?shortcode=recordindex"><i class="icon-list-alt"></i> Indextable shortcode</a></li>
				<li<?php if ( $_GET['shortcode'] == 'posttype-builder' ) echo ' class="active"'; ?>><a href="<?php echo get_permalink($post->ID); ?>/?shortcode=posttype-builder"><i class="icon-th-list"></i> Post type builder</a></li>
				<li<?php if ( $_GET['shortcode'] == 'fieldset-builder' ) echo ' class="active"'; ?>><a href="<?php echo get_permalink($post->ID); ?>/?shortcode=fieldset-builder"><i class="icon-th-large"></i> Fieldset builder</a></li>
				<li<?php if ( $_GET['shortcode'] == 'field-builder' ) echo ' class="active"'; ?>><a href="<?php echo get_permalink($post->ID); ?>/?shortcode=field-builder"><i class="icon-th"></i> Field builder</a></li>
				<li<?php if ( $_GET['shortcode'] == 'task-builder' ) echo ' class="active"'; ?>><a href="<?php echo get_permalink($post->ID); ?>/?shortcode=task-builder"><i class="icon-th"></i> Task builder</a></li>
			</ul>
			<?php

			switch ( $_GET['shortcode'] ) :
				case null :
					?>
                    <div class="alert alert-info fade in">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <strong>How To!</strong> Use this page to help you get setup!
                    </div>
					<?php
                break;
				case 'recordform' :
                    do_shortcode("[generator_recordform]");
                break;
				case 'recordindex' :
                    do_shortcode("[generator_recordindex]");
                break;
                case 'posttype-builder' :
                    do_shortcode("[posttype_builder id='PosttypeBuilder']");
                break;
				case 'fieldset-builder' :
                    do_shortcode("[fieldset_builder  id='FieldsetBuilder']");
                break;
				case 'field-builder' :
                    do_shortcode("[field_builder id='FieldBuilder']");
                break;
				case 'task-builder' :
                    do_shortcode("[task_builder id='TaskBuilder']");
                break;
			endswitch;
	}

    /**
     * Get data for the generator forms & build option strings for select boxes
     *
     */
    protected function get_gen_form_data() {
		// Declare DB Global for use throughout shourtcode
		global $wpdb;
		// Get Post types from DB
		$web_apper_cpts  = get_option( 'web_apper_cpts', array() );
		foreach ( $web_apper_cpts as $cpt_id => $cpt ) :
			$this->web_apper_cpts_options .= '<option value="' . $cpt_id . '">' . $cpt['name'] . '</option>';
		endforeach;
		// Get fieldsets from DB
		$fieldsetsTable = $wpdb->prefix . 'web_apper_fieldsets';
		$this->web_apper_fieldsets = $wpdb->get_results(
			'SELECT * FROM ' . $fieldsetsTable,
			'ARRAY_A'
		);
		foreach ( $this->web_apper_fieldsets as $fieldset ) :
			$this->web_apper_fieldsets_options .= '<option value="' . $fieldset['fieldset_id'] . '">' . $fieldset['fieldset_name'] . '</option>';
		endforeach;
		// Get fields from DB
		$fieldsTable = $wpdb->prefix . 'web_apper_fields';
		$web_apper_fields = $wpdb->get_results(
			"SELECT * FROM $fieldsTable ORDER BY fieldset ASC",
			'ARRAY_A'
		);
		foreach ( $web_apper_fields as $field ) :
			$this->web_apper_fields_options .= '<option value="' . $field['field_id'] . '">' . $field['field_name'] . '</option>';
		endforeach;
		// Set Cap field option string
		$this->wp_user_caps =
			'<option></option>' .
			'<option value="logged_out">logged out</option>' .
			'<option value="read">read</option>' .
			'<option value="edit_posts">edit posts</option>' .
			'<option value="edit_others_posts">edit others posts</option>' .
			'<option value="edit_users">edit users</option>' .
			'<option value="edit_pages">edit pages</option>' .
			'<option value="edit_plugins">edit plugins</option>';
	}

    /**
     * Adds ajax & javascript for generator
     *
     */
    protected function add_generator_js() {
		?>
		<script type="text/javascript">
			jQuery(document).ready(function($) {
				// Attach a submit handler for the generator form
					$("form#generator_form").submit(function() {
						$('#tab-form-fields .span12').remove();  // Remove alert in the form fields tab that may be open with parent div
						$('.alert').alert('close');  // Close any alerts that may be open
						var data = {
							action: 'web_apper<?php echo $this->shortcode; ?>',
							nonce: '<?php echo wp_create_nonce('WebApperAwesomeness!87'); ?>',
							formData: $("form#generator_form").serializeArray(),
							shortcode: '<?php echo $_GET['shortcode']; ?>',
						};
						$.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
							var result = $.parseJSON(response);  // Parse JSON response
							$("#shortcode").html(result.shortcode);  // Insert into Modal
							$("#shortcode").css('text-align', 'left');
							$("#generator_form").prepend(result.htmlalert);  // Insert into Modal
						});
						return false;
					});
				
				// Associative array of fields by fieldset
					fieldsBySet = [];
						<?php
						global $wpdb;
						foreach ( $this->web_apper_fieldsets as $fieldset ) :
							$fieldsetID = $fieldset['fieldset_id'];
							$fieldsTable = $wpdb->prefix . 'web_apper_fields';
							$web_apper_fields = $wpdb->get_results(
								"SELECT * FROM $fieldsTable WHERE fieldset = '$fieldsetID' ORDER BY field_order ASC",
								'ARRAY_A'
							);
							if ( !empty($web_apper_fields) ) :
								echo 'fieldsBySet[\'' . $fieldsetID . '\'] = [';
								foreach ( $web_apper_fields as $field ) :
									echo ' \'<option value="' . $field['field_id'] . '">' . $field['field_name'] . '</option>\',' . "\n";
								endforeach;
								echo " ]; \n";
							endif;
						endforeach;
						?>
					
				
				// Set change event handler for the 'fieldset' field
					$('#generator_form [name="fieldset"]').on('change', function() {
						var aSelected = $(this).val();
						setExcludeOptions(this);  // Set Exclude select options
						setIncludeOptions(this);  // Set Include select options
						if ( aSelected == null )  {  // If no fieldset is selected
							$('#generator_form [name="exclude"]').attr('disabled', '');  // Disable Exclude select
							$('#generator_form [name="include"]').removeAttr('disabled');  // Enable Include select
						}
					});
				// Set change event handler for the 'view' field
					$('#generator_form [name="view"]').on('change', function() {
						//var aSelected = $(this).val();
						if ( $(this).val() == 'Modal' )  {
							$('#generator_form [name="modalbtn"]').removeAttr('disabled');
							$('#generator_form [name="modalheading"]').removeAttr('disabled');
						} else {
							$('#generator_form [name="modalbtn"]').val('').attr('disabled', '');
							$('#generator_form [name="modalheading"]').val('').attr('disabled', '');
						}						});
				// Set change event handler for the 'editor' field
					$('#generator_form [name="editor"]').on('change', function() {
						//var aSelected = $(this).val();
						if ( $(this).val() == 'true' )
							$('#generator_form [name="titlefield"]').removeAttr('disabled');
						else
							$('#generator_form [name="titlefield"]').attr('disabled', '');
					});
				// Set change event handlers to set 'titlefield'
					$('#generator_form [name="fieldset"]').on('change', function() {
						setTitleOptions();  // Set 'titlefield' select options
						setLinkedOptions();  // Set 'linkedfield' select options
					});
					$('#generator_form [name="include"]').on('change', function() {
						setTitleOptions();  // Set 'titlefield' select options
						setLinkedOptions();  // Set 'linkedfield' select options
					});
					$('#generator_form [name="exclude"]').on('change', function() {
						setTitleOptions();  // Set 'titlefield' select options
						setLinkedOptions();  // Set 'linkedfield' select options
					});
	
				// Set the Exclude select options
					function setExcludeOptions(el) {
						var aSelected = $(el).val();
						var aExcludeOptions = [];
						aSelected.map( function(item) {
							if ( fieldsBySet[item] != undefined )
								aExcludeOptions = aExcludeOptions.concat(fieldsBySet[item]);
						});
						$('#generator_form [name="exclude"]').html(aExcludeOptions);
						if ( 0 < aExcludeOptions.length ) {
							$('#generator_form [name="exclude"]').removeAttr('disabled');
						} else {
							$('#generator_form [name="exclude"]').attr('disabled', '');
						}
					}
				// Set the Include select options
					function setIncludeOptions(el) {
						var aSelected = $(el).val();
						var aIncludeOptions = [];
						for ( var key in fieldsBySet ) {
							if ( !fieldsBySet.hasOwnProperty(key) ) {
								continue;
							}
							aIncludeOptions[key] = fieldsBySet[key];
						}
						aSelected.map( function(item) {
							if ( aIncludeOptions[item] != undefined )
								delete aIncludeOptions[item];
						});
						aIncludeOptionsFinal = [];
						for ( var key in aIncludeOptions ) {
							if ( !fieldsBySet.hasOwnProperty(key) ) {
								continue;
							}
							aIncludeOptionsFinal = aIncludeOptionsFinal.concat( fieldsBySet[key] );
						};
						$('#generator_form [name="include"]').html(aIncludeOptionsFinal);
						if ( 0 < aIncludeOptionsFinal.length ) {
							$('#generator_form [name="include"]').removeAttr('disabled');
						} else {
							$('#generator_form [name="include"]').attr('disabled', '');
						}
					}
				// Set the Title Field select options
					function setTitleOptions() {
						var sTitleOptions = '';
						$('#generator_form [name="include"] option').each(function(i) {
							if ( $(this)[0].selected == true ) {
								sTitleOptions = sTitleOptions + '<option value="' + this.value + '">' + this.innerText + '</option>';
							}
						});
						$('#generator_form [name="exclude"] option').each(function(i) {
							if ( $(this)[0].selected == false ) {
								sTitleOptions = sTitleOptions + '<option value="' + this.value + '">' + this.innerText + '</option>';
							}
						});
						$('#generator_form [name="titlefield"]').html(sTitleOptions);
					}
				// Set the Linked Field select options
					function setLinkedOptions() {
						var sLinkedOptions = '<option></option>';
						$('#generator_form [name="include"] option').each(function(i) {
							if ( $(this)[0].selected == true ) {
								sLinkedOptions = sLinkedOptions + '<option value="' + this.value + '">' + this.innerText + '</option>';
							}
						});
						$('#generator_form [name="exclude"] option').each(function(i) {
							if ( $(this)[0].selected == false ) {
								sLinkedOptions = sLinkedOptions + '<option value="' + this.value + '">' + this.innerText + '</option>';
							}
						});
						$('#generator_form [name="linkedfield"]').html(sLinkedOptions);
					}
	
			});
				
		</script>
		<?php
	}

    /**
     * Handles ajax requests
     *
     * @since 1.0
     */
	function sendAjaxResponse() {
		check_ajax_referer( 'WebApperAwesomeness!87', 'nonce' );
		echo json_encode( $this->generator_add() );
		die();  // Prevents ajax from returning a '0'
	}

    /**
     * Generates a new shortcode string
     *
     */
	public function generator_add() {
		
		$formData =  $_POST['formData'];  // Get assoc array of form field name => value pairs
		
		// Set error messages
		$errormsgs = array();
		$errormsgs['id'] = "Please complete the 'Form ID' field.";
		$errormsgs['idAlphaNumer'] = "Please be sure the 'Form ID' field is AlphaNumeric.";
		$errormsgs['posttype'] = "Please select an option from the 'Post Type' field.";
		$errormsgs['fieldset-include'] = "Please select at least one option from the 'Fieldset' or 'Include' field.";
		$errormsgs['titlefield'] = "Please select at least one option from the 'Post title field' field.";
		if ( $_POST['shortcode'] == 'form' ) :
			$errormsgs['modalbtn'] = "Please complete the 'Modal button label' field.";
			$errormsgs['modalheading'] = "Please complete the 'Modal Heading' field.";
		endif;

		$shortcode = '['.$_POST['shortcode'];  // Open the shortcode string
		$once = true;
		
		// Build the shortcode string
		foreach ( $formData as $attr ) :  // Foreach form field,
			// Unset error messages
			if ( $attr['name'] == 'id' && !empty($attr['value'])  ) :
				unset( $errormsgs['id'] );
				if ( filter_var( $attr['value'], FILTER_VALIDATE_REGEXP, array('options' => array('regexp'=> '/^[a-zA-Z0-9\_]+$/')) )  ) :
					unset( $errormsgs['idAlphaNumer'] );
				endif;
			elseif ( $attr['name'] == 'fieldset' || $attr['name'] == 'include' ) :  // Require 1 of these fields
				unset( $errormsgs['fieldset-include'] );
			elseif ( $attr['name'] == 'editor' && $attr['value'] == 'false' ) :  // Unset modal warnings if 'Modal' view is not selected
				unset( $errormsgs['titlefield'] );
			elseif ( $attr['name'] == 'view' && $attr['value'] != 'Modal' ) :  // Unset modal warnings if 'Modal' view is not selected
				unset( $errormsgs['modalbtn'] );
				unset( $errormsgs['modalheading'] );
			elseif ( array_key_exists( $attr['name'], $errormsgs ) && !empty($attr['value']) ) :
				unset( $errormsgs[ $attr['name'] ] );
			endif;
			// Add the shortcode attributes
			if ( !empty($attr['value']) ) :  // if field value is not empty,
				if ( $prev == $attr['name'] ) :
					$shortcode .= ',' . $attr['value'];  // add the value.
				else :
					if ( $once === false ) :  // Dont close attr value the first iteration
						$shortcode .= '\'';
					endif;
					$shortcode .= ' ' . $attr['name'] . '=\'' . $attr['value'];  // add the value.
				endif;
			endif;
			$prev = $attr['name'];
			$once = false;
		endforeach;
		if ( !empty($formData) ) :  // Check if there is an attr value to close
			$shortcode .= '\']';  // Close the shortcode string
		else :
			$shortcode .= ']';  // Close the shortcode string
		endif;
		// Check if there is any errors to display
		if ( empty($errormsgs) ) :
			$response = array(
				'shortcode' => $shortcode,
				'htmlalert' => '<div class="alert alert-success fade in"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Hurray!</strong> Shortcode Updated</div>',
			);
		else :
			$htmlalert = '<div class="alert alert-error fade in"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Oh snap!</strong> ';
			foreach ( $errormsgs as $errormsg ) :
				$htmlalert .= '<br />' . $errormsg;
			endforeach;
			$htmlalert .= '</div>';
			$response = array(
				'shortcode' => '[' . $_POST['shortcode'] . ']',
				'htmlalert' => $htmlalert,
			);
		endif;
		return $response;
	}
	
}

$initialize = new Generator(); 

?>